package com.first.nell.components.form

import android.annotation.SuppressLint
import android.content.Context
import android.text.Editable
import android.text.TextWatcher
import android.util.AttributeSet
import android.util.TypedValue
import android.view.View
import android.widget.RelativeLayout
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentManager
import com.first.nell.R
import com.first.nell.base.BaseFormAction
import com.first.nell.data.RevObjInfoPageFieldConfig
import com.first.nell.databinding.ViewFirstNellFormInputOtpBinding
import com.first.nell.extend.addFirstNellHighlightFirstNellStyle
import com.first.nell.extend.recordFirstNellTagFirstNellEvent
import com.first.nell.extend.toFirstNell00FirstNellFormat
import com.first.nell.utils.analytics.util.AnalyticsUtil
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*

/**
<declare-styleable name="FirstNellFormInput">
<attr name="cwfiTitle" format="string" />
<attr name="cwfiText" format="string" />
<attr name="cwfiHint" format="string" />
<attr name="cwfiTitleColor" format="color" />
<attr name="cwfiTextColor" format="color" />
<attr name="cwfiHintColor" format="color" />
<attr name="cwfiTitleSize" format="dimension" />
<attr name="cwfiTextSize" format="dimension" />
</declare-styleable>
 * */
class InputOtpForm : RelativeLayout,
    com.first.nell.components.form.BaseFormAction,
    BaseFormAction {

    lateinit var mFirstNellViewFirstNellBinding: ViewFirstNellFormInputOtpBinding
    private lateinit var vFirstNellRootFirstNellView: View

    private var cwfiTitleColor: Int = 0
    private var cwfiTextColor: Int = 0
    private var cwfiHintColor: Int = 0
    private var cwfiTitle: String? = null
    private var cwfiText: String? = null
    private var cwfiHint: String? = null
    private var cwfiTitleSize: Float = 0F
    private var cwfiTextSize: Float = 0F

    private var onFirstNellFormFirstNellConfig: RevObjInfoPageFieldConfig? = null
    private var OnFirstNellStateFirstNellChangedFirstNellListener: (Int, String) -> Unit =
        { action, content -> }
    private var mFirstNellSupportFirstNellFragmentFirstNellManager: FragmentManager? = null

    private var mFirstNellTempFirstNellInputFirstNellValue: String = ""
    private var mFirstNellOnFirstNellActionFirstNellClickFirstNellListener: (Int) -> Unit = {}
    private var mFirstNellOnFirstNellTextFirstNellChangedFirstNellListener: (String) -> Unit =
        { text -> }

    private var mFirstNellCutdownFirstNellFlow: Job? = null

    constructor(context: Context?) : this(context, null)
    constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : this(
        context,
        attrs,
        defStyleAttr,
        0
    )

    @SuppressLint("Recycle")
    constructor(
        context: Context?,
        attrs: AttributeSet?,
        defStyleAttr: Int,
        defStyleRes: Int,
    ) : super(
        context,
        attrs,
        defStyleAttr,
        defStyleRes
    ) {
        attrs?.let {
            context?.let { cxt ->
                val array =
                    cxt.obtainStyledAttributes(
                        attrs,
                        R.styleable.InputOtpForm
                    )
                cwfiTitleColor = array.getColor(
                    R.styleable.InputOtpForm_cwfioTitleColor,
                    ContextCompat.getColor(cxt, R.color.main_black)
                )
                cwfiTitle =
                    array.getString(R.styleable.InputOtpForm_cwfioTitle)

                cwfiTextColor = array.getColor(
                    R.styleable.InputOtpForm_cwfioTextColor,
                    ContextCompat.getColor(cxt, R.color.main_black)
                )
                cwfiText =
                    array.getString(R.styleable.InputOtpForm_cwfioText)

                cwfiHintColor = array.getColor(
                    R.styleable.InputOtpForm_cwfioHintColor,
                    ContextCompat.getColor(cxt, R.color.input_hint)
                )
                cwfiHint =
                    array.getString(R.styleable.InputOtpForm_cwfioHint)

                cwfiTitleSize = array.getDimension(
                    R.styleable.InputOtpForm_cwfioTitleSize,
                    resources.getDimensionPixelSize(
                        R.dimen.sp_14
                    ).toFloat()
                )

                cwfiTextSize = array.getDimension(
                    R.styleable.InputOtpForm_cwfioTextSize,
                    resources.getDimensionPixelSize(
                        R.dimen.sp_14
                    ).toFloat()
                )

                array.recycle()
            }
        }
        context?.let {
            vFirstNellRootFirstNellView =
                View.inflate(it, R.layout.view_first_nell_form_input_otp, this)
            mFirstNellViewFirstNellBinding =
                ViewFirstNellFormInputOtpBinding.bind(vFirstNellRootFirstNellView)
            initFirstNellSubviews()
        }
    }

//    override fun onAttachedToWindow() {
//        super.onAttachedToWindow()
//        println("====onAttachedToWindow")
//        updateUIDisplay()
//    }

    override fun initFirstNellSubviews() {
        try {
            mFirstNellViewFirstNellBinding.textFormInputTitle.text = (cwfiTitle)
            mFirstNellViewFirstNellBinding.textFormInputTitle.setTextColor(cwfiTitleColor)
            mFirstNellViewFirstNellBinding.textFormInputTitle.setTextSize(
                TypedValue.COMPLEX_UNIT_PX,
                cwfiTitleSize
            )

            mFirstNellViewFirstNellBinding.editFormInput.setText(cwfiText)
            mFirstNellViewFirstNellBinding.editFormInput.setTextColor(cwfiTextColor)
            mFirstNellViewFirstNellBinding.editFormInput.setTextSize(
                TypedValue.COMPLEX_UNIT_PX,
                cwfiTextSize
            )

            mFirstNellViewFirstNellBinding.editFormInput.hint = (cwfiHint)
            mFirstNellViewFirstNellBinding.editFormInput.setHintTextColor(cwfiHintColor)

            mFirstNellViewFirstNellBinding.editFormInput.setOnFocusChangeListener { _, b ->
                if (!b) {
                    isFirstNellFormFirstNellCompleted()
                    val gContent = getFirstNellContent()
                    if (gContent.isNotBlank()) {
                        if (!gContent.equals(
                                mFirstNellTempFirstNellInputFirstNellValue,
                                false
                            )
                        ) {
                            try {
                                mFirstNellTempFirstNellInputFirstNellValue = gContent
                                if (tag != null) {
                                    var gTag = tag as String
                                    if (gTag.isNotBlank()) {
                                        gTag = "INPUT_$gTag"
                                        AnalyticsUtil.saveHitPointInfo(
                                            type = gTag,
                                            remark = gContent)
                                    }
                                }
                            } catch (e: Exception) {
                                e.printStackTrace()
                            }
                        }
                    }
                } else {
                    //判断是否显示删除按键
                }
            }
            mFirstNellViewFirstNellBinding.editFormInput.addTextChangedListener(object :
                TextWatcher {
                override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                }

                override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                }

                override fun afterTextChanged(p0: Editable?) {
                    //判断是否显示删除按键
                    val tempContent = getFirstNellContent()
                    onFirstNellFormFirstNellConfig?.fillContent = tempContent
                    //回调
                    mFirstNellOnFirstNellTextFirstNellChangedFirstNellListener.invoke(
                        tempContent
                    )
                }
            })

            //增加星号显示
            mFirstNellViewFirstNellBinding.textFormInputTitle.addFirstNellHighlightFirstNellStyle(
                mutableListOf("*"),
                ContextCompat.getColor(context, R.color.main_red)
            )

            mFirstNellViewFirstNellBinding.textFormInputSend.setOnClickListener {
                val gText = mFirstNellViewFirstNellBinding.textFormInputSend.text.toString().trim()
                if (gText.contains("OTP")) {
                    mFirstNellOnFirstNellActionFirstNellClickFirstNellListener.invoke(0)
                    //记录打点
                    mFirstNellViewFirstNellBinding.textFormInputSend.recordFirstNellTagFirstNellEvent()
                }
            }

        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }

    override fun setFirstNellDetail(detail: String) {
        setFirstNellContent(detail)
    }

    override fun setFirstNellDetailFirstNellColor(detailColor: Int) {

    }

    override fun setFirstNellTitleFirstNellColor(titleColor: Int) {

    }

    override fun setFirstNellContent(content: String) {
        mFirstNellViewFirstNellBinding.editFormInput.setText(content)
        onFirstNellFormFirstNellConfig?.fillContent = content

        if (content.isNotBlank()) {
            mFirstNellViewFirstNellBinding.textFormInputErrTip.visibility = GONE
            mFirstNellViewFirstNellBinding.rlFormInputContentBg.setBackgroundResource(R.drawable.first_nell_form_input)
        }
    }

    fun getFirstNellContent(): String {
        return mFirstNellViewFirstNellBinding.editFormInput.text.toString().trim()
    }

    override fun setFirstNellTitle(title: String) {
        cwfiTitle = title
        mFirstNellViewFirstNellBinding.textFormInputTitle.text = (cwfiTitle)
        //增加星号显示
        mFirstNellViewFirstNellBinding.textFormInputTitle.addFirstNellHighlightFirstNellStyle(
            mutableListOf("*"),
            ContextCompat.getColor(context, R.color.main_red)
        )
    }

    override fun setFirstNellHint(hint: String) {
        cwfiHint = hint
        mFirstNellViewFirstNellBinding.editFormInput.hint = (cwfiHint)
    }

    override fun setFirstNellFormFirstNellConfig(item: RevObjInfoPageFieldConfig) {
        onFirstNellFormFirstNellConfig = item
        tag = item.paramName
        updateFirstNellUIFirstNellDisplay()
        item.fillContent?.let { fillContent ->
            setFirstNellContent(fillContent)
        }
        if (item.needCheckComplete == true) {
            isFirstNellFormFirstNellCompleted()
        }
    }

    override fun setFirstNellOnFirstNellStateFirstNellChangedFirstNellListener(listener: (Int, String) -> Unit) {
        OnFirstNellStateFirstNellChangedFirstNellListener = listener
    }

    override fun isFirstNellFormFirstNellCompleted(): Boolean {
        val gcontent = getFirstNellContent()
        if (gcontent.isBlank()) {
            if (onFirstNellFormFirstNellConfig != null) {
                if (onFirstNellFormFirstNellConfig?.isFirstNellMustFirstNellFill() == true) {
                    mFirstNellViewFirstNellBinding.rlFormInputContentBg.setBackgroundResource(R.drawable.first_nell_form_input_error)
                    mFirstNellViewFirstNellBinding.textFormInputErrTip.visibility = VISIBLE
                }
            } else {
                mFirstNellViewFirstNellBinding.rlFormInputContentBg.setBackgroundResource(R.drawable.first_nell_form_input_error)
                mFirstNellViewFirstNellBinding.textFormInputErrTip.visibility = VISIBLE
            }
            return false
        }

        mFirstNellViewFirstNellBinding.textFormInputErrTip.visibility = GONE
        mFirstNellViewFirstNellBinding.rlFormInputContentBg.setBackgroundResource(R.drawable.first_nell_form_input)
        return true
    }

    override fun isFirstNellFormFirstNellCompletedFirstNellSilent(): Boolean {
        val gcontent = getFirstNellContent()
        if (gcontent.isBlank()) {
            return false
        }
        return true
    }

    fun updateFirstNellUIFirstNellDisplay() {
        setFirstNellTitle(onFirstNellFormFirstNellConfig?.title.toString())
        setFirstNellHint(onFirstNellFormFirstNellConfig?.hint.toString())
    }

    override fun setFirstNellFragmentFirstNellManager(manager: FragmentManager) {
        mFirstNellSupportFirstNellFragmentFirstNellManager = manager
    }

    override fun setFirstNellOnFirstNellActionFirstNellClickFirstNellListener(listener: (Int) -> Unit) {
        mFirstNellOnFirstNellActionFirstNellClickFirstNellListener = listener
    }

    fun setFirstNellOnFirstNellTextFirstNellChangedFirstNellListener(listener: (String) -> Unit) {
        mFirstNellOnFirstNellTextFirstNellChangedFirstNellListener = listener
    }

    private fun initFirstNellCutdownFirstNellFlow(
        scope: CoroutineScope,
        onTick: (Int) -> Unit,
        onFinish: () -> Unit,
    ): Job {
        return flow {
            for (tickSec in 60 downTo 0) {
                emit(tickSec)
                if (tickSec != 0) {
                    delay(1000)
                }
            }
        }.flowOn(Dispatchers.Main)
            .onEach { onTick.invoke(it) }
            .onCompletion { onFinish.invoke() }
            .launchIn(scope)
    }

    @SuppressLint("SetTextI18n")
    fun startFirstNellCutdown(scope: CoroutineScope) {
        mFirstNellCutdownFirstNellFlow = initFirstNellCutdownFirstNellFlow(scope,
            {
                if (it == 0) {
                    mFirstNellCutdownFirstNellFlow?.cancel()
                }
                mFirstNellViewFirstNellBinding.textFormInputSend.text =
                    "${it.toFirstNell00FirstNellFormat()}s"
            },
            {
                mFirstNellViewFirstNellBinding.textFormInputSend.text = "Gửi mã OTP"
            })
    }

    fun stopFirstNellCutdown() {
        mFirstNellCutdownFirstNellFlow?.cancel()
    }

}

